package com.ruitaowang.admin.view.api;

import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.core.domain.PcUser;
import com.ruitaowang.core.domain.Role;
import com.ruitaowang.core.domain.SysUser;
import com.ruitaowang.core.domain.Verifycode;
import com.ruitaowang.core.utils.RandomUtils;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.PcUserService;
import com.ruitaowang.goods.service.VerifyCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@RestController
public class APIUserController extends BaseController {

    @Autowired
    private PcUserService pcUserService;
    @Autowired
    private VerifyCodeService verifyCodeService;

    /**
     * 商城登录
     * @param phone
     * @param password
     * @return
     */
    @RequestMapping(value = "/api/admin/login", method = RequestMethod.GET)
    public String login(String phone,String password){
        PcUser pcUser = new PcUser();
        PcUser pcUser1;
        pcUser.setPhone(phone);
        List<PcUser> pcUsers = pcUserService.select(pcUser);
        if (ObjectUtils.isEmpty(pcUsers)) {
            return this.renderJson(MsgOut.error("该用户未注册！"));
        } else {
            pcUser1 = pcUsers.get(0);
        }
        LOGGER.info("password={}, needPassword={}", password, pcUser1.getPassword());
        if (passwordEncoder().matches(password, pcUser1.getPassword())) {
            setSessionAttribute("user",pcUser1);
            return this.renderJson(MsgOut.success(pcUser1));
        } else {
            return this.renderJson(MsgOut.error("用户名或密码错误"));
        }
    }
    
    /**
     * 注册
     * @param pcUser
     * @param checkcode
     * @return
     */
    @RequestMapping(value = "/api/admin/register", method = RequestMethod.PUT)
    public String register(PcUser pcUser, String checkcode){
        //检测验证码是否有效
        Verifycode v = new Verifycode();
        v.setMobile(pcUser.getPhone());
        List<Verifycode> verifycodes = verifyCodeService.select(v);
        v = verifycodes.get(0);
        //检测全局缓存中的code与传过来的code是否匹配
        LOGGER.info("checkcode == " + checkcode);
        LOGGER.info("v.getVerifycode() == " + v.getVerifycode());
        if (!checkcode.equals(v.getVerifycode())) {
            return this.renderJson(MsgOut.error("验证码错误！"));
        }
        pcUser.setPassword(RandomUtils.hashPassword(pcUser.getPassword()));
        String userName = getUserName(9);
        pcUser.setUsername(userName);
        pcUserService.insert(pcUser);
        setSessionAttribute("user",pcUser);
        return this.renderJson(MsgOut.success(pcUser));
    }

    public String getUserName(int length){
        String val = "ruitao_";
        Random random = new Random();

        for (int i = 0;i < length;i++){
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if("char".equalsIgnoreCase(charOrNum)){
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char)(random.nextInt(26) + temp);
            } else if ("num".equalsIgnoreCase(charOrNum)){
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

    /**
     * 检查手机号
     * @param pcUser
     * @return
     */
    @RequestMapping(value = "/api/admin/checkPhone", method = RequestMethod.GET)
    public String checkPhone(PcUser pcUser){
        List<PcUser> sysUserList = pcUserService.select(pcUser);
        if (!ObjectUtils.isEmpty(sysUserList)) {
            return this.renderJson(MsgOut.error("该手机号已注册，请联系管理员修改"));
        }
        return this.renderJson(MsgOut.success());
    }

    /**
     * 检查是否登录
     * @param session
     * @return
     */
    @RequestMapping(value = "/api/admin/checkLogin", method = RequestMethod.GET)
    public String checkLogin(HttpSession session){
        PcUser pcUser = (PcUser) session.getAttribute("user");
        if (!ObjectUtils.isEmpty(pcUser)) {
            return this.renderJson(MsgOut.success(pcUser));
        } else {
            return this.renderJson(MsgOut.error("未登录"));
        }
    }

    @RequestMapping(value = "/api/admin/logout", method = RequestMethod.GET)
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return this.renderJson(MsgOut.success());
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    protected HttpServletRequest getRequest(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return servletRequestAttributes.getRequest();
    }
    
    protected HttpSession getSession(){
        return getRequest().getSession();
    }

    protected void setSessionAttribute(String k, Object v){
        getSession().setAttribute(k, v);
    }
}
